package com.pluszg.nutrition.common.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

import static org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration.APPLICATION_TASK_EXECUTOR_BEAN_NAME;

@Configuration
@EnableAsync(proxyTargetClass = true)
@Slf4j
public class ExecutorConfig {

    @Lazy
    @Primary
    @Bean(name = APPLICATION_TASK_EXECUTOR_BEAN_NAME)
    public ThreadPoolTaskExecutor asyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        int cpuNum = Runtime.getRuntime().availableProcessors();// 获取处理器数量
        log.debug("cpu num: {}", cpuNum);
        int threadNum = cpuNum * 2 + 1;// 根据cpu数量,计算出合理的线程并发数

        //配置核心线程数
        executor.setCorePoolSize(threadNum);
        //配置最大线程数
        executor.setMaxPoolSize(threadNum + 1);
        //配置队列大小
        executor.setQueueCapacity(200);
        //当池子的线程数大于corePoolSize时，多余的线程会等待keepAliveTime长时间，如果无请求可处理就自行销毁
        //即闲置线程存活时间
        executor.setKeepAliveSeconds(60);
        //配置线程池中的线程的名称前缀
        executor.setThreadNamePrefix("task-exec-");
        // rejection-policy：当pool已经达到max size的时候，如何处理新任务
        // CALLER_RUNS：不在新线程中执行任务，而是有调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //执行初始化
        //executor.initialize();

        return executor;
    }
}
